package sein.android.hopenote;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import sein.android.hopenote.Const.HopeNoteDb;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.mocoplex.adlib.AdlibActivity;


public class Note_Search extends AdlibActivity {
	
	private DBAdapter HnopenHelper;
	private SQLiteDatabase sdb;
	private String str_Item, str_User, str_Unit, str_Cnt;
	private	Cursor list_cur;
	private EditText et_fr, et_to;
	private Button btn_show;
	private	TextView tv_item, tv_unit;
	private	ListView lv_search;
	private	ArrayList<SearchData> Search_arr;
	private SearchAdapter S_adapter;
	private int iYear, iMonth, iDay;
	static final int DATE_DIALOG_ID = 0;
	private View v_et;
	private String mSdPath;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.note_search);
		
		IntentFilter filter_reset = new IntentFilter("Reset");
		registerReceiver(BR_Note_Search,filter_reset);
		IntentFilter filter_fileout = new IntentFilter("Fileout_item");
		registerReceiver(BR_Note_Search_Fileout,filter_fileout);
		IntentFilter filter_Emailout = new IntentFilter("Emailout_item");
		registerReceiver(BR_Note_Search_Emailout,filter_Emailout);
		
		HnopenHelper = new DBAdapter(this);
        sdb = HnopenHelper.getReadableDatabase();
        
        str_User = "";
        str_Item = "";
        str_Unit = "";
        str_Cnt = "";

		et_fr  = (EditText)findViewById(R.id.et_fr);
		et_to = (EditText)findViewById(R.id.et_to);
		btn_show = (Button)findViewById(R.id.btn_show);

        //Intent intent = getIntent();
		//str_User = getString(R.string.user_name);	// 사용자 명
        str_User = HopeNoteDb.CURRENT_USER;	// 사용자 명
		str_Item = HopeNoteDb.CURRENT_ITEM;	// 항목 명
		str_Unit = HopeNoteDb.CURRENT_UNIT;	// 단위
		str_Cnt = HopeNoteDb.CURRENT_CNT;	// 입력 수
		
		// 광고 호출
		this.setAdsContainer(R.id.ads);
		
		SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date();
		
		et_to.setText(dateformat.format(date));
		date.setDate(1);
		et_fr.setText(dateformat.format(date));
		
		DateTimeInit();
		
		// DB
		String getColumns[] = {"strftime('%m'," + HopeNoteDb.COL_DATE + ")", "strftime('%d'," + HopeNoteDb.COL_DATE + ")","strftime('%H:%M'," + HopeNoteDb.COL_DATE + ")",HopeNoteDb.COL_DOCUMENT1,HopeNoteDb.COL_DOCUMENT2, HopeNoteDb.COL_IDX};
        String qWhere = HopeNoteDb.COL_USER + " = '" + str_User + "' AND " + HopeNoteDb.COL_ITEM + " = '" + str_Item + "'" + " AND strftime('%Y-%m-%d'," + HopeNoteDb.COL_DATE + ") BETWEEN '" + et_fr.getText().toString() + "' AND '" + et_to.getText().toString() + "'";
        list_cur = sdb.query(HopeNoteDb.TB_NOTE, getColumns, qWhere, null, null, null, "strftime('%m'," + HopeNoteDb.COL_DATE + "), strftime('%d'," + HopeNoteDb.COL_DATE + ")");
        list_cur.moveToFirst();
        
        // Insert into Array
        Search_arr = new ArrayList<SearchData>();
        SearchData datarow;
        String mon = "";
        String s_mon = "";
        String day = "";
        String s_day = "";
        for(int i = 0; i < list_cur.getCount(); i++){
        	s_mon = list_cur.getString(0) + "월";
        	if(mon.equals(list_cur.getString(0)))
        	{
        		s_mon = "";
        	}
        	s_day = list_cur.getString(1) + "일"; 
        	if(day.equals(list_cur.getString(1)))
        	{
        		s_day = "";
        	}
        	datarow = new SearchData(s_mon, s_day, list_cur.getString(2),list_cur.getString(3),list_cur.getString(4), list_cur.getString(5));
        	Search_arr.add(datarow);
        	mon = list_cur.getString(0);
        	day = list_cur.getString(1);
        	list_cur.moveToNext();
        }
        list_cur.close();
        
        // Custom Adapter
        S_adapter = new SearchAdapter(this, R.layout.note_search_row,Search_arr);
        
        tv_item = (TextView)findViewById(R.id.tv_item);
        tv_item.setText(str_Item);
        tv_unit = (TextView)findViewById(R.id.tv_unit);
        tv_unit.setText("단위 : " + str_Unit);
        lv_search = (ListView)findViewById(R.id.lv_search);
        lv_search.setAdapter(S_adapter);
        
        // 보기 버튼
        btn_show.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				et_fr.clearFocus();
				et_to.clearFocus();
				
				if(HopeNoteDb.CURRENT_USER.equals(""))
				{
					Toast.makeText(Note_Search.this, "메뉴키를 눌러 사용자를 선택해주세요.", Toast.LENGTH_SHORT).show();
				}
				else if(HopeNoteDb.CURRENT_ITEM.equals(""))
				{
					Toast.makeText(Note_Search.this, "메뉴키를 눌러 항목 선택해주세요.", Toast.LENGTH_SHORT).show();
				}
				else
				{
					reset();
				}
			}
		});
        
        // 년/월 자동완
        et_fr.addTextChangedListener(new TextWatcher() {
			
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				int fr = Integer.valueOf(et_fr.getText().toString().replace("-", ""));
				int to = Integer.valueOf(et_to.getText().toString().replace("-", ""));
				if(fr > to)
				{
					et_to.setText(s.toString());
				}
			}
		});
        
        et_to.addTextChangedListener(new TextWatcher() {
			
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				// TODO Auto-generated method stub
				
			}
			
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub
				
			}
			
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				int fr = Integer.valueOf(et_fr.getText().toString().replace("-", ""));
				int to = Integer.valueOf(et_to.getText().toString().replace("-", ""));
				if(fr > to)
				{
					et_fr.setText(s.toString());
				}
			}
		});
        
        // DatePicker
        et_fr.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				v_et = v;
				showDialog(DATE_DIALOG_ID);
			}
		});
        
        et_to.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				v_et = v;
				showDialog(DATE_DIALOG_ID);
			}
		});
	}
	
	
	
	//검색 결과 (날짜/값) 데이터 클래스
	class SearchData{
		String mon;
		String day;
		String time;
		String idx;
		String document1;
		String document2;
		SearchData(String _mon, String _day, String _time, String _document1, String _document2, String _idx){
			mon = _mon;
			day = _day;
			time = _time;
			idx = _idx;
			document1 = _document1;
			document2 = _document2;
		}
	}
	
	//검색 결과 어댑터 클래스
	class SearchAdapter extends BaseAdapter{
		Context context;
		int layoutId;
		ArrayList<SearchData> ResultDataArr;
		LayoutInflater Inflater;
		SearchAdapter(Context _context, int _layoutId, ArrayList<SearchData> _ResultDataArr){
			context = _context;
			layoutId = _layoutId;
			ResultDataArr = _ResultDataArr;
			Inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}
		
		public int getCount(){
			return ResultDataArr.size();
		}
		
		public Object getItem(int position){
			return ResultDataArr.get(position);
		}
		
		public long getItemId(int position)
		{
			return position;
		}
		
		public View getView(int position, View convertView, ViewGroup parent){
			final int pos = position;
			if(convertView == null){
				convertView = Inflater.inflate(layoutId, parent,false);
			}
			
			TextView tv_mon = (TextView)convertView.findViewById(R.id.tv_mon);
			TextView tv_day = (TextView)convertView.findViewById(R.id.tv_day);
			TextView tv_time = (TextView)convertView.findViewById(R.id.tv_time);
			tv_mon.setText(ResultDataArr.get(position).mon);
			tv_day.setText(ResultDataArr.get(position).day);
			tv_time.setText(ResultDataArr.get(position).time);
			if(str_Cnt.equals("1"))
			{
				TextView tv_document1 = (TextView)convertView.findViewById(R.id.tv_document1);
				tv_document1.setText(ResultDataArr.get(position).document1);
				
			}
			else
			{
				TextView tv_document1 = (TextView)convertView.findViewById(R.id.tv_document1);
				tv_document1.setText(ResultDataArr.get(position).document1 + "   " + ResultDataArr.get(position).document2);
				
			}
			
			convertView.setOnClickListener(new View.OnClickListener() {
				
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					HopeNoteDb.MODIFY_IDX = ResultDataArr.get(pos).idx;
					Intent intent = new Intent(Note_Search.this, Note_Mod.class);
					startActivity(intent);
				}
			});
			
			return convertView;
		}
	}
	
	
	private void reset() {
		// TODO Auto-generated method stub
		str_User = HopeNoteDb.CURRENT_USER;
		str_Item = HopeNoteDb.CURRENT_ITEM;
		str_Unit = HopeNoteDb.CURRENT_UNIT;	// 단위
		str_Cnt = HopeNoteDb.CURRENT_CNT;	// 입력 수
		
		tv_item.setText(str_Item);
		tv_unit.setText("단위 : " + str_Unit);
		
		// DB
		String getColumns[] = {"strftime('%m'," + HopeNoteDb.COL_DATE + ")", "strftime('%d'," + HopeNoteDb.COL_DATE + ")","strftime('%H:%M'," + HopeNoteDb.COL_DATE + ")",HopeNoteDb.COL_DOCUMENT1,HopeNoteDb.COL_DOCUMENT2, HopeNoteDb.COL_IDX};
        String qWhere = HopeNoteDb.COL_USER + " = '" + str_User + "' AND " + HopeNoteDb.COL_ITEM + " = '" + str_Item + "'" + " AND strftime('%Y-%m-%d'," + HopeNoteDb.COL_DATE + ") BETWEEN '" + et_fr.getText().toString() + "' AND '" + et_to.getText().toString() + "'";
        list_cur = sdb.query(HopeNoteDb.TB_NOTE, getColumns, qWhere, null, null, null, "strftime('%m'," + HopeNoteDb.COL_DATE + "), strftime('%d'," + HopeNoteDb.COL_DATE + ")");
        list_cur.moveToFirst();
        
        // Insert into Array
        Search_arr.clear();
        SearchData datarow;
        String mon = "";
        String s_mon = "";
        String day = "";
        String s_day = "";
        for(int i = 0; i < list_cur.getCount(); i++){
        	s_mon = list_cur.getString(0) + "월";
        	if(mon.equals(list_cur.getString(0)))
        	{
        		s_mon = "";
        	}
        	s_day = list_cur.getString(1) + "일"; 
        	if(day.equals(list_cur.getString(1)))
        	{
        		s_day = "";
        	}
        	datarow = new SearchData(s_mon, s_day, list_cur.getString(2),list_cur.getString(3),list_cur.getString(4), list_cur.getString(5));
        	Search_arr.add(datarow);
        	mon = list_cur.getString(0);
        	day = list_cur.getString(1);
        	list_cur.moveToNext();
        }
        list_cur.close();

        S_adapter.notifyDataSetChanged();
	}
	
	public void DateTimeInit()
	{
		final Calendar objTime = Calendar.getInstance();
        iYear = objTime.get(Calendar.YEAR);
        iMonth = objTime.get(Calendar.MONTH);
        iDay = objTime.get(Calendar.DAY_OF_MONTH);
	}
	
	protected Dialog onCreateDialog(int id)
	{
		switch(id)
		{
		case DATE_DIALOG_ID:
			return new DatePickerDialog(getParent(), mDateSetListener, iYear, iMonth, iDay);
		}
		return null;
	}
	
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			// TODO Auto-generated method stub
			iYear = year;
			iMonth = monthOfYear;
			iDay = dayOfMonth;
			
			if(v_et.getId() == R.id.et_fr)
			{
				updateDisplay(et_fr);
			}
			else if(v_et.getId() == R.id.et_to)
			{
				updateDisplay(et_to);
			}
		}
	};
	
	private void updateDisplay(EditText et)
	{
		String tMon, tDay;
		tMon = Integer.toString(iMonth+1);
		tDay = Integer.toString(iDay);
		if(tMon.length() == 1)
		{
			tMon = "0" + tMon;
		}
		if(tDay.length() == 1)
		{
			tDay = "0" + tDay;
		}
		
		et.setText(new StringBuilder().append(iYear).append("-").append(tMon).append("-").append(tDay));
	}
		
	private BroadcastReceiver BR_Note_Search = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
	        reset();
		}
	};
	
	//csv file output
	private BroadcastReceiver BR_Note_Search_Fileout = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			
			StringBuilder sb = new StringBuilder();
			
			String ext = Environment.getExternalStorageState();
			if(ext.equals(Environment.MEDIA_MOUNTED)){
				mSdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
			}else{
				mSdPath = Environment.MEDIA_UNMOUNTED;
			}
			
			try{				
				// directory 생성
				File dir = new File(mSdPath + "/hopenote");
				dir.mkdir();
				
				// 파일 생성
				SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmss");
				Date date = new Date();
				String szFileName = str_Item+"_"+et_fr.getText().toString().replace("-", "")+et_to.getText().toString().replace("-", "")+"_"+dateformat.format(date)+".csv";
				File file = new File(mSdPath + "/hopenote/" + szFileName);
				
				if (!file.exists()){
	            	mSdPath = "";
	            }else{
	            	AlertDialog.Builder ad = new AlertDialog.Builder(Note_Search.this);
	            	ad.setMessage("파일 생성 실패");
	            	ad.setPositiveButton(android.R.string.ok, null);
	            	ad.setTitle("Error");
	            	ad.show();
	            	return;
	            }
				
	            WritableWorkbook workbook = null;
	     	    WritableSheet sheet = null;
	
	     	   
	     	    try{
	     	    	
					//FileOutputStream fos = new FileOutputStream(file);
					//FileOutputStream excelFile = openFileOutput(szFileName, Context.MODE_WORLD_WRITEABLE);
					sb.append("success create file");
	
		        	long start = 0;
		        	long end = 0;
		        	       	
		        	
		        	
    	            //workbook = Workbook.createWorkbook(excelFile);
	        		workbook = Workbook.createWorkbook(file);
    	            workbook.createSheet("sheet1", 0);
    	            sheet = workbook.getSheet(0);
	                sheet.addCell(new Label(0, 0, str_Item));
	                sheet.addCell(new Label(0, 1, "월"));
	                sheet.addCell(new Label(1, 1, "일"));
	                sheet.addCell(new Label(2, 1, "시간"));
	                sheet.addCell(new Label(3, 1, "값1"));
	                sheet.addCell(new Label(4, 1, "값2"));
	                
	                // DB
    	    		String getColumns[] = {"strftime('%m'," + HopeNoteDb.COL_DATE + ")", "strftime('%d'," + HopeNoteDb.COL_DATE + ")","strftime('%H:%M'," + HopeNoteDb.COL_DATE + ")",HopeNoteDb.COL_DOCUMENT1,HopeNoteDb.COL_DOCUMENT2, HopeNoteDb.COL_IDX};
    	            String qWhere = HopeNoteDb.COL_USER + " = '" + str_User + "' AND " + HopeNoteDb.COL_ITEM + " = '" + str_Item + "'" + " AND strftime('%Y-%m-%d'," + HopeNoteDb.COL_DATE + ") BETWEEN '" + et_fr.getText().toString() + "' AND '" + et_to.getText().toString() + "'";
    	            list_cur = sdb.query(HopeNoteDb.TB_NOTE, getColumns, qWhere, null, null, null, "strftime('%m'," + HopeNoteDb.COL_DATE + "), strftime('%d'," + HopeNoteDb.COL_DATE + ")");
    	            list_cur.moveToFirst();
    	            
    	            // Insert into Array
    	            String mon = "";
    	            String s_mon = "";
    	            String day = "";
    	            String s_day = "";
    	            for(int i = 0; i < list_cur.getCount(); i++){
    	            	s_mon = list_cur.getString(0);
    	            	if(mon.equals(list_cur.getString(0)))
    	            	{
    	            		s_mon = "";
    	            	}
    	            	s_day = list_cur.getString(1); 
    	            	if(day.equals(list_cur.getString(1)))
    	            	{
    	            		s_day = "";
    	            	}
    	                sheet.addCell(new Label(0, i+2, s_mon));
    	                sheet.addCell(new Label(1, i+2, s_day));
    	                sheet.addCell(new Label(2, i+2, list_cur.getString(2)));
    	                sheet.addCell(new Label(3, i+2, list_cur.getString(3)));
    	                sheet.addCell(new Label(3, i+2, list_cur.getString(4)));
    	                
    	                mon = list_cur.getString(0);
    	            	day = list_cur.getString(1);
    	            	list_cur.moveToNext();
    	            }
    	            
    	            list_cur.close();

    	            workbook.write();
    	            workbook.close();
    	            
    	            Toast.makeText(Note_Search.this, "hopenote/"+szFileName+" 저장 완료", Toast.LENGTH_LONG).show();
					
				}catch(FileNotFoundException e){
					sb.append("========file not found err : " + e.toString());
				}catch(SecurityException e){
					sb.append("========Security Exception  err: " + e.toString());
				}catch(Exception e){
					sb.append("======== Exception  err: " + e.toString());
				}
				
			}catch(Exception e){
				sb.append("btn_write_test err : " + e.toString() );
			}
			Log.i("log",sb.toString());
		}
	};
	
	
	//csv file to Email
		private BroadcastReceiver BR_Note_Search_Emailout = new BroadcastReceiver() {
			
			@Override
			public void onReceive(Context context, Intent intent) {
				// TODO Auto-generated method stub
				
				StringBuilder sb = new StringBuilder();
				
				String ext = Environment.getExternalStorageState();
				if(ext.equals(Environment.MEDIA_MOUNTED)){
					mSdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
				}else{
					mSdPath = Environment.MEDIA_UNMOUNTED;
				}
				
				try{				
					// directory 생성
					File dir = new File(mSdPath + "/hopenote");
					dir.mkdir();
					// 파일 생성
					SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmss");
					Date date = new Date();
					String szFileName = str_Item+"_"+et_fr.getText().toString().replace("-", "")+et_to.getText().toString().replace("-", "")+"_"+dateformat.format(date)+".csv";
					File file = new File(mSdPath + "/hopenote/" + szFileName);

					if (!file.exists()){
		            	mSdPath = "";
		            }else{
		            	AlertDialog.Builder ad = new AlertDialog.Builder(Note_Search.this);
		            	ad.setMessage("파일 생성 실패");
		            	ad.setPositiveButton(android.R.string.ok, null);
		            	ad.setTitle("Error");
		            	ad.show();
		            	return;
		            }
					
		            WritableWorkbook workbook = null;
		     	    WritableSheet sheet = null;
		
		     	   
		     	    try{
		     	    	
						//FileOutputStream fos = new FileOutputStream(file);
						//FileOutputStream excelFile = openFileOutput(szFileName, Context.MODE_WORLD_WRITEABLE);
						sb.append("success create file");
		
			        	long start = 0;
			        	long end = 0;
			        	       	
			        	
			        	
	    	            //workbook = Workbook.createWorkbook(excelFile);
		        		workbook = Workbook.createWorkbook(file);
	    	            workbook.createSheet("sheet1", 0);
	    	            sheet = workbook.getSheet(0);
		                sheet.addCell(new Label(0, 0, str_Item));
		                sheet.addCell(new Label(0, 1, "월"));
		                sheet.addCell(new Label(1, 1, "일"));
		                sheet.addCell(new Label(2, 1, "시간"));
		                sheet.addCell(new Label(3, 1, "값1"));
		                sheet.addCell(new Label(4, 1, "값2"));
		                
		                // DB
	    	    		String getColumns[] = {"strftime('%m'," + HopeNoteDb.COL_DATE + ")", "strftime('%d'," + HopeNoteDb.COL_DATE + ")","strftime('%H:%M'," + HopeNoteDb.COL_DATE + ")",HopeNoteDb.COL_DOCUMENT1,HopeNoteDb.COL_DOCUMENT2, HopeNoteDb.COL_IDX};
	    	            String qWhere = HopeNoteDb.COL_USER + " = '" + str_User + "' AND " + HopeNoteDb.COL_ITEM + " = '" + str_Item + "'" + " AND strftime('%Y-%m-%d'," + HopeNoteDb.COL_DATE + ") BETWEEN '" + et_fr.getText().toString() + "' AND '" + et_to.getText().toString() + "'";
	    	            list_cur = sdb.query(HopeNoteDb.TB_NOTE, getColumns, qWhere, null, null, null, "strftime('%m'," + HopeNoteDb.COL_DATE + "), strftime('%d'," + HopeNoteDb.COL_DATE + ")");
	    	            list_cur.moveToFirst();
	    	            
	    	            // Insert into Array
	    	            String mon = "";
	    	            String s_mon = "";
	    	            String day = "";
	    	            String s_day = "";
	    	            for(int i = 0; i < list_cur.getCount(); i++){
	    	            	s_mon = list_cur.getString(0);
	    	            	if(mon.equals(list_cur.getString(0)))
	    	            	{
	    	            		s_mon = "";
	    	            	}
	    	            	s_day = list_cur.getString(1); 
	    	            	if(day.equals(list_cur.getString(1)))
	    	            	{
	    	            		s_day = "";
	    	            	}
	    	                sheet.addCell(new Label(0, i+2, s_mon));
	    	                sheet.addCell(new Label(1, i+2, s_day));
	    	                sheet.addCell(new Label(2, i+2, list_cur.getString(2)));
	    	                sheet.addCell(new Label(3, i+2, list_cur.getString(3)));
	    	                sheet.addCell(new Label(3, i+2, list_cur.getString(4)));
	    	                
	    	                mon = list_cur.getString(0);
	    	            	day = list_cur.getString(1);
	    	            	list_cur.moveToNext();
	    	            }
	    	            
	    	            list_cur.close();

	    	            workbook.write();
	    	            workbook.close();
	    	            
	    	            Toast.makeText(Note_Search.this, "hopenote/"+szFileName+" 저장 완료", Toast.LENGTH_LONG).show();
						
					}catch(FileNotFoundException e){
						sb.append("========file not found err : " + e.toString());
					}catch(SecurityException e){
						sb.append("========Security Exception  err: " + e.toString());
					}catch(Exception e){
						sb.append("======== Exception  err: " + e.toString());
					}
		     	    
		     	    Uri fileUri = Uri.fromFile(file);
					
		     	   Intent it = new Intent(Intent.ACTION_SEND);
					it.setType("plane/text");
					
					// 수신인 주소 - tos배열의 값을 늘릴 경우 다수의 수신자에게 발송됨
					//String[] tos = { "h_zilla@hotmail.com" };
					//it.putExtra(Intent.EXTRA_EMAIL, tos);
					it.putExtra(Intent.EXTRA_SUBJECT, "");
					it.putExtra(Intent.EXTRA_TEXT, "");
					it.putExtra(Intent.EXTRA_STREAM, fileUri);
					startActivity(it);
		     	    
				}catch(Exception e){
					sb.append("btn_write_test err : " + e.toString() );
				}
				Log.i("log",sb.toString());
			}
		};
		
	
	@Override
	public void onAttachedToWindow() {
		// TODO Auto-generated method stub
		super.onAttachedToWindow();

		reset();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(BR_Note_Search);
		unregisterReceiver(BR_Note_Search_Fileout);
	};
}
